bt.module({builder: function(bt) {
    var photoList = $('#photo-list'),
        wpList,
        addText = $('#add-text-item'),
        map,
        currentMarker,
        path,
        markers,
        infoWindows,
        currentInfoWindowIndex = -1,
        tripDay,
        photoArrow = $('#photo-arrow'),
        wayPointHero = $('#edit-waypoint-hero'),
        wayPointHeroOrder = $('#edit-waypoint-hero-order'),
        wayPointHeroOrderSave = $('#edit-waypoint-hero-order-save'),
        wayPointHeroOrderCancel = $('#edit-waypoint-hero-order-cancel'),
        wayPointOrderMode = 0,
        wayPointText = $('#edit-waypoint-text'),
        poiArea = $('#poi-area'),
        timeFullArea = $('#time-full-area'),
        timeFull = $('#time-full'),
        timeFullPopup = $('#time-full-popup'),
        privacy = $('#privacy'),
        privacyArea = $('#privacy-area'),
        privacySet = $('#privacy-set'),
        privacyPopup = $('#privacy-popup'),
        timeSelect = $('#time-select'),
        text = $('#text'),
        date = $("#date"),
        year = $('#year'),
        month = $('#month'),
        day = $('#day'),
        hour = $('#hour'),
        min = $('#min'),
        sec = $('#sec'),
        latitude = $('#latitude'),
        longitude = $('#longitude'),
        editSaveYes = $('#edit-waypoint-save-yes'),
        currentWaypointItem,
        isRefreshingPhotoList = false; //是否是保存wappoint之后刷新tripday列表中
    var Page = {
        initPhotoEvents : function () {
            wpList = $('#wp');
            tripDay = $('#days');
            this.initDayNav();
            this.initWaypointDelete();
            wpList.on('click', '.wp-item',Page.selectWaypoint);
        },
        initDayNav : function(){
            var watchDayNav = function () {
                var wpDays = wpList.find('li');
                
                wpDays.each(function(index,item) {
                    //waypoint滚动条里第一个top为正的元素，即为当前滚动到的区域所对应的元素
                    if ($(this).position().top >= 0) {
                        tripDay.find("li.cur").removeClass("cur");
                        tripDay.find("li").eq(index).addClass("cur");
                        return false;
                    }
                });
            };
            var breakNav = function () {
                var _li = tripDay.find('li'),
                    _length = _li.length;
                    _index = tripDay.find('li.cur').index(),
                    _breakt = $('#break-top'),
                    _breakb = $('#break-bottom');

                var _TopBreakAanchor = function () {
                    var _TargetTopNum = _breakt.index(),
                        _TargetBottomNum = _index - 4,
                        _TargetNum = Math.round( (_TargetBottomNum - _TargetTopNum ) / 2) + 4,
                        _Target = _li.eq(_TargetNum).find('a').attr('data-scroll');

                    _breakt.attr({
                        'data-scroll': _Target,
                        'href': _Target
                    });
                };

                var _BottomBreakAanchor = function () {
                    var _TargetTopNum = _index + 4,
                        _TargetBottomNum = _breakb.index(),
                        _TargetNum = Math.round( (_TargetBottomNum - _TargetTopNum ) / 2) + _index + 4,
                        _Target = _li.eq(_TargetNum).find('a').attr('data-scroll');

                    _breakb.attr({
                        'data-scroll': _Target,
                        'href': _Target
                    });
                };

                if ( _length > 15 ) {
                    _TopBreakAanchor();
                    _BottomBreakAanchor();
                    if ( _index <= 9 ) {
                        _li.removeClass('hidden');
                        _breakt.addClass('break-hidden');
                        _breakb.removeClass('break-hidden');
                        _li.slice(11, -3).addClass('hidden');
                    }
                    else if ( 9 < _index && _index <= _length - 9 ) {
                        _li.removeClass('hidden');
                        _breakt.removeClass('break-hidden');
                        _breakb.removeClass('break-hidden');
                        _li.slice(3, (_index - 4)).addClass('hidden');
                        _li.slice((_index + 3), -3).addClass('hidden');

                    }
                    else if ( _length <= _index + 9 ) {
                        _li.removeClass('hidden');
                        _breakt.removeClass('break-hidden');
                        _breakb.addClass('break-hidden');
                        _li.slice(3, -11).addClass('hidden');
                    }
                }
            };
            var _timer;
            this.scrollHandel = function scrollHandel(e){
                //正常状态下，waypoints滚动时，需要动态改变日期导航的选中状态
                if ( _timer ) clearTimeout(_timer);
                _timer = setTimeout(function(){
                    watchDayNav();                
                    breakNav();
                }, 200);
            }
            wpList.on('scroll',Page.scrollHandel);

            tripDay.find('a').on('click',function(e){
                e.preventDefault();
                if($(this).parent().hasClass("cur")){
                    return;
                }
                
                var _scrollAnchor = $(this).attr("data-scroll"),
                    _scrollPoint = $("#" + _scrollAnchor).position().top + wpList.scrollTop();
                
                //正在给照片排序模式
                if(wayPointOrderMode == 1){
                    wpList.scrollTop(_scrollPoint - 80);
                    var wpItemOrder = wpList.find('.wp-item-order'),
                        nextItem = $("#" + _scrollAnchor).find('.wp-item').first();
                    wpItemOrder.hide();
                    nextItem.after(wpItemOrder);
                    wpItemOrder.show();
                    var _offsetTop = wpItemOrder.offset().top - photoList.offset().top;
                    if(_offsetTop != photoArrow.position().top -32){
                        photoArrow.css('top',_offsetTop+32);
                    }
                }else{
                    wpList.scrollTop(_scrollPoint);
                }
                var _this = $(this)
                setTimeout(function(){
                    tripDay.find("li.cur").removeClass("cur");
                    _this.parent().addClass("cur");
                },300);
                
                return false;
            });
            breakNav();
        },
        initWaypointDelete : function(){
            wpList.delegate('.wp-item .delete','click',function(e){
                e.stopPropagation();
                if(confirm("真的要删除这个记录么？")) {
                    var parent = $(this).parent();
                    if(parent.hasClass('new-text-item')){
                        //编辑下一个waypoints
                        var wpItemlist = wpList.find('.wp-item'),
                            index = wpItemlist.index(parent),
                            nextItem = wpItemlist.eq(index + 1);
                        parent.remove();
                        currentWaypointItem = null;
                        nextItem.trigger('click');
                    }
                    $.ajax({
                        url: '/trips/'+ bt.context('tripid') +'/waypoints/'+parent.attr('data-id')+'/delete/',
                        type: "DELETE",
                        success: function(msg){
                            msg = eval(msg);
                            if (msg.error){
                                alert(msg.error);
                            }else{
                                Page.refreshPhotoDayNav(true);
                            }
                        }
                    });
                }
            });
        },
        selectWaypoint : function (e) {
            e.preventDefault();

            var _item = $(this);
            //如果正在照片排序，则不能编辑其他waypoint
            if(wayPointOrderMode == 1){
                return;
            }
            if(_item.hasClass('cur')){
                return;
            }
            if(currentWaypointItem && Page.isWaypointEdited() && !isRefreshingPhotoList && !confirm('您有尚未保存的改动，确定离开？')){
                return;
            }else{
                Page.resetWaypointDetail();
            }

            wpList.find('.wp-item.cur').removeClass('cur').find('.delete').hide();
            _item.addClass('cur').find('.delete').show();
            
            var offsetTop = wpList.scrollTop() + _item.position().top + _item.parent().position().top - 140;
            wpList.scrollTop(offsetTop);

            var _arrowTop = _item.offset().top - photoList.offset().top;
            if(_arrowTop != photoArrow.position().top -52){
                photoArrow.animate({
                    top : _arrowTop+52
                },500);
            }

            //对应tripday选中
            var date = $(this).parent().attr('id'),
                selectTripday = tripDay.find('a[data-scroll="'+date+'"]');
            setTimeout(function(){
                tripDay.find("li.cur").removeClass("cur");
                selectTripday.parent().addClass("cur");
            },300);
            

            Page.editWaypoint(_item);
        },
        triggerFirstWpItem : function(){
            var editId = parseInt(bt.context('editId')),
                startId = parseInt(bt.context('startId')),
                editItem = wpList.find('.wp-item[data-id="'+editId+'"]'),
                startItem = wpList.find('.wp-item[data-id="'+startId+'"]');
            if(startId && startItem.length>0){
                wpList.find('.wp-item[data-id="'+startId+'"]').trigger('click');
            }else if(editId && editItem.length>0){
                wpList.find('.wp-item[data-id="'+editId+'"]').trigger('click');
            }else{
                wpList.find('.wp-item').first().trigger('click');
            }
        },

        initWaypointDetail : function(){

            //添加文字
            addText.on('click',function(){
                var _currentWaypoint = wpList.find('.wp-item.cur'),
                    _currentTime = _currentWaypoint.attr("data-time"),
                    _textTime = moment(_currentTime).add('seconds', 10).format("YYYY-MM-DD HH:mm:ss ZZ"),
                    _textTimezone = _currentWaypoint.attr("data-tz-name");
                var _textWaypoint = [
                    '<div class="wp-item new-text-item" data-id="" title="" data-time="'+_textTime+'" data-tz-name="'+_textTimezone+'" data-privacy="0"  data-lat="" data-lng="" data-poi-id="" data-poi-name="" data-poi-type="">',
                        '<p class="text-item edit-trip-icons-waypoint-text-item"></p>',
                        '<p class="text-item edit-trip-icons-waypoint-text-item-edit"></p>',
                        '<i class="delete edit-trip-icons-delete"></i>',
                    '</div>'
                ].join('');
                _currentWaypoint.after(_textWaypoint).next().click();
                $("#text-time-unix").val(moment(_textTime).format("X"));
            });

            var wpItemList, //wp item 列表
                wpItemOrder, //占位元素
                index,  //当前选中的item的inex
                parent,
                lastStayIndex, //上一次隐藏占位元素所在item列表的index
                lastStayTop, //上一次列表的scrollTop
                photoListTop = photoList.offset().top,
                beforeWpListTop; //在排序前的列表滚动量
            var _timer;
            //鼠标滚动，每次上移或下移一格
            function mousewheelHandel(e){
                //阻止滚动
                e.preventDefault();
                if ( _timer ) clearTimeout(_timer);
                _timer = setTimeout(function(){
                    wpItemList = wpList.find('.wp-item');
                    lastStayTop = wpList.scrollTop();
                    lastStayIndex = wpItemList.index(wpItemOrder);
                    if(e.deltaY > 0){
                        //列表往上走
                        //滚到第一个上面就不再滚了
                        if(lastStayIndex == 0){
                            return;
                        }
                        //占位框往上移动一格
                        var preItem = wpItemList.eq(lastStayIndex-1);
                        wpItemOrder.hide();
                        preItem.before(wpItemOrder);
                        wpItemOrder.show();
                        //列表滚动
                        wpList.scrollTop(lastStayTop -140);

                        var _offsetTop = wpItemOrder.offset().top - photoListTop;
                        if(_offsetTop != photoArrow.position().top -52){
                            photoArrow.css('top',_offsetTop+52);
                        }
                        
                    }else{
                        //列表往下走
                        //滚到倒数第一个下面，就不再滚了
                        if(lastStayIndex == wpItemList.length ){
                            return;
                        }
                        //占位框往下移动一格
                        var nextItem = wpItemList.eq(lastStayIndex + 1);
                        wpItemOrder.hide();
                        nextItem.after(wpItemOrder);
                        wpItemOrder.show();
                        //列表滚动
                        wpList.scrollTop(lastStayTop + 140);
                        
                        var _offsetTop = wpItemOrder.offset().top - photoListTop;
                        if(_offsetTop != photoArrow.position().top -52){
                            photoArrow.css('top',_offsetTop+52);
                        }
                    }
                }, 50);
                
            }
            function orderStyleChange(){
                $('.wrap').toggleClass('waypoint-order-mode');
                $('#waypoint-order-overlay').toggleClass('hidden');
                photoList.toggleClass('waypoint-order-mode');
                $('.edit-waypoint-main').toggleClass('waypoint-order-mode');
            }
            wayPointHero.find('.img-wrapper').on('mouseover',function(){
                if(wayPointOrderMode == 0){
                    wayPointHeroOrder.show();
                }
            }).on('mouseleave',function(){
                if(wayPointOrderMode == 0){
                    wayPointHeroOrder.hide();
                }
            });
            //调整照片顺序按钮点击
            wayPointHeroOrder.on('click',function(){
                orderStyleChange();
                currentWaypointItem.find('.delete').hide();
                wpItemList = wpList.find('.wp-item');
                index = wpItemList.index(currentWaypointItem);
                parent = currentWaypointItem.parent();

                wayPointHeroOrder.hide();
                wayPointHeroOrderSave.show();
                wayPointHeroOrderCancel.show();
                //进入排序模式
                wayPointOrderMode = 1;
                //解除原有的滚动事件
                wpList.off('scroll',Page.scrollHandel);
                beforeWpListTop = wpList.scrollTop() + currentWaypointItem.position().top + parent.position().top - 140;
                wpList.animate({
                    scrollTop :beforeWpListTop
                },200,function(){
                    if(index == 0){
                        //第一个图片被选中
                        currentWaypointItem.after('<div class="wp-item wp-item-order">滚动列表调整顺序</div>');
                    }else{
                        currentWaypointItem.before('<div class="wp-item wp-item-order">滚动列表调整顺序</div>');
                    }
                    wpItemOrder = wpList.find('.wp-item-order');
                    wpItemOrder.click(function(){
                        wayPointHeroOrderSave.trigger('click');
                    });
                    var _offsetTop = wpItemOrder.offset().top - photoListTop;
                    if(_offsetTop != photoArrow.position().top -52){
                        photoArrow.css('top',_offsetTop+52);
                    }
                });
                //监听鼠标滚动，因为要实现每次滚动一格的效果
                wpList.on('mousewheel',mousewheelHandel);
                wpList.on('mousewheel',Page.scrollHandel);
            });
            wayPointHeroOrderSave.on('click',function(){
                var wpItemList = wpList.find('.wp-item'),
                    orderItemIndex = wpItemList.index(wpItemOrder),
                    preItem = orderItemIndex == 0 ? "" : wpItemList.eq(orderItemIndex-1),
                    nextItem = wpItemList.eq(orderItemIndex+1);
                //排序没有改动
                if( (preItem && preItem.get(0) == currentWaypointItem.get(0)) || nextItem.get(0) == currentWaypointItem.get(0)){
                    wayPointHeroOrderCancel.trigger('click');
                    return;
                }
                var basedItem,
                    orderedTime;
                if(orderItemIndex == 0){
                    basedItem = nextItem;
                    //在基准的waypoint的时间基础上减10s
                    orderedTime = moment(basedItem.attr('data-time')).subtract('seconds', 10).format("YYYY-MM-DD HH:mm:ss ZZ");
                }else{
                    basedItem = preItem;
                    //在基准的waypoint的时间基础上加10s
                    orderedTime = moment(basedItem.attr('data-time')).add('seconds', 10).format("YYYY-MM-DD HH:mm:ss ZZ");
                }
                

                $.ajax({
                    type: "POST",
                    url: "/create_trip/" + bt.context('tripid') + "/waypoints/" + currentWaypointItem.attr('data-id') + "/modify_datetime/",
                    data: {
                        csrfmiddlewaretoken : $('body').data('csrf'),
                        timestamp : moment(orderedTime).format("X")
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if(resp.error) {
                            alert('保存失败，请稍后重试');
                            wayPointHeroOrderCancel.trigger('click');
                        } else {
                            Page.refreshPhotoDayNav();
                            wayPointHeroOrderCancel.trigger('click');
                        }
                    },
                    error: function() {
                    }
                });

            });
            wayPointHeroOrderCancel.on('click',function(){
                orderStyleChange();
                currentWaypointItem.find('.delete').show();
                wayPointHeroOrderSave.hide();
                wayPointHeroOrderCancel.hide();
                wayPointHeroOrder.show();
                //退出排序模式
                wayPointOrderMode = 0;
                //解除鼠标滚动监听
                wpList.off('mousewheel',mousewheelHandel);
                wpList.off('mousewheel',Page.scrollHandel);
                //恢复列表原有的滚动监听
                wpList.on('scroll',Page.scrollHandel);
                wpItemOrder.remove();
                wpList.scrollTop(beforeWpListTop);
                var _arrowTop = currentWaypointItem.offset().top - photoList.offset().top;
                if(_arrowTop != photoArrow.position().top -52){
                    photoArrow.animate({
                        top : _arrowTop+52
                    },500);
                }
            });
            $('#waypoint-order-overlay').on('click',function(){
                wayPointHeroOrderCancel.trigger('click');
            });

            
            wayPointText.find('textarea').on('change',function(){
                text.val( $(this).val());
            }).on('input', function(){ //记录文字限制提示
                var $this = $(this),
                    $text = $('#edit-waypoint-text'),
                    $tip = $text.find('.tip'),
                    len = $.trim($this.val()).length;
                if(len >= 480){
                    $tip.html('还可以输入<span>'+ (500 - len) +'</span>个字');
                    if(len <= 500){
                        editSaveYes.removeClass('disabled');
                        $text.removeClass('more').addClass('near');
                    }else{
                        editSaveYes.addClass('disabled');
                        $text.removeClass('near').addClass('more');
                    }
                }else{
                    editSaveYes.removeClass('disabled');
                    $text.removeClass('near , more');
                }
            });
            timeFullArea.on('click',function(){
                timeFullPopup.show();
            }).on('mouseleave',function(){
                timeFullPopup.hide();
                Page.spliceDate();
            });
            privacySet.on('click',function(){
                privacyPopup.show();
            });
            privacyPopup.on('mouseleave',function(){
                privacyPopup.hide();
            });
            privacyPopup.find('a').click(function(){
                var privacyVal = $(this).data("value");
                if(privacyVal == 0){
                    privacySet.html('<i class="edit-trip-icons-privacy_public left-icon"></i><span>公开照片</span>').attr('data-value',0);
                }else if(privacyVal == 1){
                    privacySet.html('<i class="edit-trip-icons-privacy_friend left-icon"></i><span>好友可见</span>').attr('data-value',1);
                }else if(privacyVal == 2){
                    privacySet.html('<i class="edit-trip-icons-privacy_self left-icon"></i><span>自己可见</span>').attr('data-value',2);
                }
                privacy.val(privacyVal);
                privacyPopup.find('.selected').removeClass('selected');
                $(this).addClass('selected');
                privacyPopup.hide();
            });
            timeSelect.on('change', function() {
                var _new_tz = $(this).val();
                var _now = moment(date.attr('data-time'), "YYYY-MM-DD HH:mm:ss ZZ").tz(_new_tz);
                year.val( _now.format("YYYY") );
                month.val( _now.format("MM") );
                day.val( _now.format("DD") );
                hour.val( _now.format("HH") );
                min.val( _now.format("mm") );
                sec.val( _now.format("ss") );
                Page.spliceDate();
            });
        },

        resetWaypointDetail : function(){
            $('#edit-waypoint-text').find('.tip').html('');
            $('#edit-waypoint-save-yes').removeClass('disabled');

        },
        spliceDate: function(){
            timeFullArea.find("input").removeClass("error");
            // safari 对个位数日期处理错误
            var _inputNumber = [month, day, hour, min];
            $(_inputNumber).each(function(index, el) {
                if ( el.val().length === 1 ) {
                    el.val( "0" + el.val() );
                }
            });
            if ( year.val() !== "" ) {
                var yearVal = year.val(),
                    monthVal = month.val(),
                    dayVal = day.val(),
                    hourVal = hour.val(),
                    minVal = min.val(),
                    secVal = sec.val(),
                    tz = timeSelect.val(),
                    _date = yearVal + "-" + monthVal + "-" + dayVal + " " + hourVal + ":" + minVal + ":" + secVal;

                if ( moment(_date).isValid() ) {
                    var _offset = moment(_date).tz(tz).format("ZZ");
                    _date = moment(_date + " " + _offset, "YYYY-MM-DD HH:mm:ss ZZ").tz(tz);
                    var _alldate = _date.format("YYYY-MM-DD HH:mm");
                    date.val(yearVal + "-" + monthVal + "-" + dayVal).attr('data-time',_date.format("YYYY-MM-DD HH:mm:ssZZ"));
                    timeFull.removeClass("error").text(_alldate);
                    timeFullPopup.find('div').text(_alldate);
                }else{
                    if ( monthVal > 12 || !$.isNumeric( monthVal) ) { month.addClass("error"); }
                    if ( dayVal > 31 || !$.isNumeric( dayVal) ) { day.addClass("error"); }
                    if ( hourVal > 24 || !$.isNumeric( hourVal) ) { hour.addClass("error"); }
                    if ( minVal > 61 || !$.isNumeric( minVal) ) { min.addClass("error"); }
                    timeFull.text("时间错误，请重新选择").addClass("error");
                }
            }
        },
        initMapEvents : function () {
            if(google) {
                var myOptions = {
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = bt.gmap.createMap("map-panel", myOptions);

                bt.gmap.setOptions(map, {
                    zoom: 12,
                    minZoom: 2,
                    streetViewControl: false,
                    panControlOptions: {
                        position: google.maps.ControlPosition.RIGHT_TOP
                    },
                    zoomControlOptions: {
                        position: google.maps.ControlPosition.RIGHT_TOP
                    }
                });
                // 如果第一个 waypoint 没有 gps 信息，展示所有地图
                var latlngbounds = new google.maps.LatLngBounds();
                map.fitBounds(latlngbounds);

                bt.gmap.addListener(map, 'click', function(event) {
                    Page.placeMarker(map, event.latLng.lat(), event.latLng.lng());
                    $('#edit-waypoint-add-gps').addClass('hidden');
                });

                // render path
                var rtn = bt.tripUtils.renderPath($("#path-data"), {}, true);
                path = rtn.path;
                path.setMap(map);
                bt.gmap.panToBounds(map, rtn.bounds);

                // render markers
                markers = rtn.markers;

                infoWindows = rtn.infoWindows;

                $.each(infoWindows, function(index, infoWindow) {
                    $("#info-window-" + index + " .right-here").live("click", function(e) {
                        e.preventDefault();
                        var pos = markers[index].getPosition();
                        Page.placeMarker(map, pos.lat(), pos.lng());
                        $('#edit-waypoint-add-gps').addClass('hidden');
                    });
                });

                $.each(markers, function(index, marker) {
                    marker.setMap(map);
                    marker.setZIndex(10);
                    bt.gmap.addListener(marker, 'click', function() {
                        if(currentInfoWindowIndex >= 0) {
                            infoWindows[currentInfoWindowIndex].close();
                        }
                        infoWindows[index].open(map, markers[index]);
                        currentInfoWindowIndex = index;
                    });
                });

                Page.triggerFirstWpItem();
            }
            var GPSPopup = $('#gps-popup');
            function showFullMapPopup (e) {
                e.preventDefault();
                bt.misc.showPopup(GPSPopup, function () {
                    $('#map-panel').appendTo('#gps-popup-map');
                    bt.gmap.refreshMap(map);
                    // overlay 添加事件
                    $('#overlay').on('click', hideFullMapPopup);
                },true);
            }
            function hideFullMapPopup (e) {
                e.preventDefault();
                $('#map-panel').prependTo('#edit-waypoint-edit-gps');
                // overlay 移除事件
                $('#overlay').off('click', hideFullMapPopup);
                bt.gmap.refreshMap(map);
                if ( currentMarker ) {
                    var _lat = currentMarker.getPosition().lat(),
                    _lng = currentMarker.getPosition().lng();
                    bt.gmap.panTo(map, _lat, _lng);
                }
                if(currentInfoWindowIndex >= 0) {
                    infoWindows[currentInfoWindowIndex].close();
                }
            }
            function searchAddress (e) {
                e.preventDefault();
                var _input = $('#gps-popup-search-input');
                var _address = _input.val();
                _input.blur();
                if($.trim(_address)) {
                    bt.gmap.searchAddress(map, _address, function(result) {
                        var latLng = result[0].geometry.location;
                        Page.placeMarker(map, latLng.lat(), latLng.lng());
                        $('#edit-waypoint-add-gps').addClass('hidden');
                    });
                }
            }
            $('#edit-waypoint-add-gps, #map-fullscreen').on('click', showFullMapPopup);
            GPSPopup.find('.close').on('click', hideFullMapPopup);
            $('#gps-popup-search-btn').on('click', searchAddress);
            $('#gps-popup-search-input').on('keydown', function (e) {
                
                if ( e.keyCode === 13 ) {
                    searchAddress(e);
                }
            });
        },
        refreshMapPath : function(trip_id) {
            $.ajax({
                type: "GET",
                url: "/trips/" + trip_id + "/path/",
                success: function(resp) {
                    $("#path-data").html(resp);
                    var rtn = bt.tripUtils.renderPath($("#path-data ol"), {}, true);
                    if(path) {
                        path.setMap(null);
                    }
                    path = rtn.path;
                    path.setMap(map);

                    $.each(markers, function(index, marker) {
                        if(marker) {
                            marker.setMap(null);
                            marker = null;
                        }
                    });

                    $.each(infoWindows, function(index, infoWindow) {
                        if(infoWindow) {
                            infoWindow.close();
                            infoWindow.setMap(null);
                            marker = null;
                        }
                    });

                    markers = rtn.markers;
                    infoWindows = rtn.infoWindows;
                    $.each(infoWindows, function(index, infoWindow) {
                        $("#info-window-" + index + " .right-here").live("click", function() {
                            var pos = markers[index].getPosition();
                            Page.placeMarker(map, pos.lat(), pos.lng());
                        });
                    });

                    $.each(markers, function(index, marker) {
                        marker.setMap(map);
                        marker.setZIndex(10);
                        bt.gmap.addListener(marker, 'click', function() {
                            if(currentInfoWindowIndex >= 0) {
                                infoWindows[currentInfoWindowIndex].close();
                            }
                            infoWindows[index].open(map, markers[index]);
                            currentInfoWindowIndex = index;
                        });
                    });
                }
            });
        },
        placeMarker : function(map, lat, lng, donotUpdateTimeZone) {
            /*
             * Temp remove gmap dependency
             */
            if(google) {
                if (currentMarker) {
                    currentMarker.setMap(null);
                }

                currentMarker = bt.gmap.createMarker({
                    draggable: true,
                    animation: google.maps.Animation.DROP,
                    position: bt.gmap.createLatLng(lat, lng),
                    map: map,
                    zIndex: google.maps.Marker.MAX_ZINDEX
                });

                Page.updateMarkerLocation(donotUpdateTimeZone);
                bt.gmap.addListener(currentMarker, 'dragend', Page.updateMarkerLocation);
            }
        },
        updateMarkerLocation : function (donotUpdateTimeZone) {
            var latLng = currentMarker.getPosition();
            latitude.val(latLng.lat());
            longitude.val(latLng.lng());
            if(!donotUpdateTimeZone){
                $.ajax({
                    url: "/query_timezone/",
                    data: {lat: latLng.lat(),
                           lng: latLng.lng()},
                    success: function(resp) {
                        timeSelect.val(resp.timezone);
                        timeSelect.change();
                    }
                });
            }
        },
        preloadImages : function (itemObj) {
            // get next & prev 3 waypoints' photo
            var _preloadimages = [],
                _wpItemlist = wpList.find('.wp-item'),
                _index = _wpItemlist.index(currentWaypointItem),
                _start = _index > 3 ? _index - 3 : 0,
                _end = _index + 4 < _wpItemlist.length ? _index + 4 : _wpItemlist.length,
                _nextItems = _wpItemlist.slice(_start, _end);
            $(_nextItems).each(function(i, el) {
                if ( $(el).find('.photo-item').length > 0 ) {
                    _preloadimages.push($(el).find('.photo-item').attr('data-photo'));
                }
            });

            $(_preloadimages).each(function(){
                $('<img/>')[0].src = this;
            });
        },
        editWaypoint : function(itemObj,cancelClick){
            
            currentWaypointItem = itemObj;
            if(!cancelClick){
                //照片和简介框样式设置
                var _type = itemObj.find('.text-item').length === 0 ? 'photo' : 'text';
                // 判断 Waypoint 类型
                if ( _type == 'photo' ) {
            
                    var _img = itemObj.find('.photo-item').data('photo'),
                        _imgW = itemObj.find('.photo-item').data('photo-w'),
                        _imgH = itemObj.find('.photo-item').data('photo-h'),
                        imgWrapper = wayPointHero.find('.img-wrapper');
                        img = wayPointHero.find('img');
                    imgWrapper.hide();
                    if(_imgW/_imgH >= 620/412){
                        img.css({
                            'width':'620px',
                            'height': 'auto'
                        }).attr('src',_img).on('load',function(){
                            imgWrapper.css({
                                'width' : '620px',
                                'height' : 620*_imgH/_imgW,
                                'top': (412-620*_imgH/_imgW)/2
                            }).show();
                            wayPointHero.parent().removeClass('edit-waypoint-main-text-mode');
                        });
                    }else{
                        img.css({
                            'height':'412px',
                            'width' : 'auto'
                        }).attr('src',_img).on('load',function(){
                            imgWrapper.css({
                                'height' : '412px',
                                'width' : 412*_imgW/_imgH,
                                'top':0
                            }).show();
                            wayPointHero.parent().removeClass('edit-waypoint-main-text-mode');
                        });
                    }
                    
                    
                }else{
                    wayPointHero.parent().addClass('edit-waypoint-main-text-mode');
                    wayPointHero.find('img').attr('src','');
                }
            }
            
            var _text = itemObj.attr('title');
            wayPointText.find('textarea').val(_text);
            text.val(_text);

            //poi设置
            if(itemObj.attr('data-poi-id')){
                poiArea.attr({
                    'data-poi-id':itemObj.attr('data-poi-id'),
                    'data-poi-meta':itemObj.attr('data-poi-meta'),
                    'data-poi-type':itemObj.attr('data-poi-type')
                }).html('<i class="left-icon poi-icons-'+(itemObj.attr('data-poi-meta')||'poi')+'_'+itemObj.attr('data-poi-type')+'_square"></i><span>'+itemObj.attr('data-poi-name')+'</span>');
            }else{
                poiArea.attr({
                    'data-poi-id':'',
                    'data-poi-meta':'',
                    'data-poi-type':''
                }).html('<i class="left-icon poi-icons-poi_11_square"></i><span>添加拍照地点</span>');
            }

            //时间和时区设置
            var _old_time = moment(itemObj.attr("data-time"), "YYYY-MM-DD HH:mm:ss ZZ").tz(itemObj.attr("data-tz-name"));
            year.val(_old_time.format("YYYY"));
            month.val(_old_time.format("MM"));
            day.val(_old_time.format("DD"));
            hour.val(_old_time.format("HH"));
            min.val(_old_time.format("mm"));
            sec.val(_old_time.format("ss"));
            timeSelect.val(itemObj.attr("data-tz-name"));
            Page.spliceDate();

            //隐私权限设置
            var photoPrivacyVal = itemObj.attr('data-privacy') || 0;
            var tripPrivacyVal = parseInt(bt.context('tripPrivacy'), 10);
            var privacyVal = tripPrivacyVal >= photoPrivacyVal ? tripPrivacyVal : photoPrivacyVal;
            privacyPopup.find('.selected').removeClass('selected');
            if(privacyVal == 0){
                privacySet.html('<i class="edit-trip-icons-privacy_public left-icon"></i><span>公开照片</span>').attr('data-value',0);
                privacyPopup.find('.privacy_public').addClass('selected');
            }else if(privacyVal == 1){
                privacySet.html('<i class="edit-trip-icons-privacy_friend left-icon"></i><span>好友可见</span>').attr('data-value',1);
                privacyPopup.find('.privacy_friend').addClass('selected');
            }else if(privacyVal == 2){
                privacySet.html('<i class="edit-trip-icons-privacy_self left-icon"></i><span>自己可见</span>').attr('data-value',2);
                privacyPopup.find('.privacy_self').addClass('selected');
            }
            privacy.val(photoPrivacyVal);

            // refresh map
            var _lat = currentWaypointItem.attr('data-lat'),
            _lng = currentWaypointItem.attr('data-lng');
            latitude.val("");
            longitude.val("");
            if ( _lat && _lng ) {
                $('#edit-waypoint-add-gps').addClass('hidden');
                Page.renderMap(map, _lat, _lng);
            }else{
                $('#edit-waypoint-add-gps').removeClass('hidden');
                currentMarker && currentMarker.setMap(null);
            }

            // preload images
            Page.preloadImages(itemObj);

            isRefreshingPhotoList = false;
        },
        renderMap : function (map, lat, lng) {
            if(!google) {
                return;
            }
            lat = parseFloat(lat);
            lng = parseFloat(lng);
            Page.placeMarker(map, lat, lng, true);
            bt.gmap.setZoom(map, 12);
            bt.gmap.panTo(map, lat, lng);
            
            bt.gmap.refreshMap(map);
        },
        initAddPoiPopup : function(){
            var poiMap,
                poiMarker,
                currentPoiInfo = {
                    id : 0,
                    value : '',
                    label : '',
                    location : '',
                    type : '',
                    meta : 'poi',
                    lat : '',
                    lng : '',
                    tel : ''
                },
                new_poi_index = 0;

            var addPoiPop = $('#add-poi-popup'),
                addPoiPopClose = addPoiPop.find('.close'),
                contentList = addPoiPop.find('.content-list'),
                contentSearch = addPoiPop.find('.content-search'),
                searchInput = contentSearch.find(".search-input input"),
                addPoiBtn = contentSearch.find('.add-new-poi'),
                autocompleteResult = contentSearch.find('.autocomplete'),
                poiListwrap = contentSearch.find('.poi-result-list-wrap'),
                emptyList = contentSearch.find('.empty-list'),
                predictList = contentSearch.find('.poi-predict-list'),
                needToClose = false;

            function initPopupDialog(){
                poiArea.click(function(){
                    var _lat = currentWaypointItem.attr('data-lat'),
                        _lng = currentWaypointItem.attr('data-lng'),
                        _poiid = poiArea.attr('data-poi-id');
                    //有GPS信息并且没有POI绑定，展示gps周围推荐信息
                    if(!_poiid && _lat && _lng){
                        $.ajax({
                            url : "/create_trip/search_nearby_poi/",
                            type : 'GET',
                            data: {
                                lon : _lng,
                                lat : _lat
                            },
                            dataType: 'json',
                            success: function(resp){
                                if(resp && resp.length > 0){
                                    poiListwrap.addClass('empty');
                                    predictList.empty();
                                    for(var i=0;i<resp.length;i++){
                                        var address = $.trim(resp[i].location);
                                        var poiItem = $("<li class='result-item " + resp[i].meta + resp[i].type + "'>")
                                        .append('<i class="poi-icon"></i><p class="title">'+ resp[i].label +'</p><p class="address">'+ address +'</p>')
                                        .data("item", resp[i]);
                                        poiItem.appendTo(predictList);
                                    }
                                    emptyList.hide();
                                    predictList.show();
                                }else{
                                    poiListwrap.addClass('empty');
                                    emptyList.show();
                                    predictList.hide();
                                }
                            },
                            error : function(){
                                poiListwrap.addClass('empty');
                                emptyList.show();
                                predictList.hide();
                            }
                        });
                    }else{
                        poiListwrap.addClass('empty');
                        emptyList.show();
                        predictList.hide();
                    }
                    bt.misc.showPopupAbsolute(addPoiPop);
                });
                addPoiPopClose.click(function(){
                    bt.misc.hidePopup(addPoiPop);
                });
            }
            //两个界面之间滑动
            function contentSwipe(direction,callback){
                if(direction == 'right'){
                    addPoiPopClose.hide();
                }
                contentList.animate({
                    left: direction == 'left' ?'0px':'-480px'
                },500,function(){
                    if(direction == 'left'){
                        addPoiPopClose.show();
                    }
                    if(callback){
                        callback();
                    }
                });
            }
            function initSearch(){

                searchInput.keydown(function(e) {
                    var code = e.which;
                    if (code == 13) {
                        $(this).autocomplete("search", $(this).val());
                        e.preventDefault();
                    }
                });
                /*
                 * AUTO_COMPLETE DATA STRUCTURE
                 * {
                 *     id: <ciphered ID>,
                 *     meta: "[poi|place]"    # "type" ==> POI;
                 *                             # "place" ==> City/Province/Country/Attraction;
                 *     type: <type>,
                 *     value: "<POI/Place name>",
                 *     label: "<Displayed POI/Place name>",
                 *     location: "<Address/Geo location>",
                 *     lat: "<Latitude>",
                 *     lng: "<Longitude>",
                 * }
                 */
                var autocompleteWidget;
                searchInput.autocomplete({
                    delay: 500,
                    appendTo: autocompleteResult,
                    source: '/create_trip/poi_search_autocomplete/',
                    search : function(e, ui){
                        //关掉上一次的搜索结果
                        needToClose = true;
                        searchInput.autocomplete( "close" );
                    },
                    response: function(e, ui) {
                        contentSearch.find('.poi-result-list-wrap').removeClass('empty');
                        emptyList.hide();
                        predictList.hide();
                        if(ui.content.length == 0){
                            addPoiBtn.show();
                        }
                    },
                    open: function(e, ui) {
                        autocompleteWidget = $(this).autocomplete("widget");
                        addPoiBtn.hide();
                        addPoiBtn.clone().appendTo(autocompleteWidget).show();
                    },
                    close: function(e, ui) {
                        contentSearch.find('.poi-result-list-wrap').addClass('empty');
                        emptyList.show();
                    }
                }).autocomplete( "instance" )._renderItem = function(ul,item){
                    var poiItem = _renderItem(item);
                    poiItem.appendTo(ul);
                    return poiItem;
                };

                function _renderItem(item){
                    var address = $.trim(item.location);
                    var poiItem = $("<li class='result-item " + item.meta + item.type + "'>")
                    .append('<i class="poi-icon"></i><p class="title">'+ item.label +'</p><p class="address">'+ address +'</p>')
                    .data("item", item);
                    
                    return poiItem;
                }
                var originalCloseMethod = searchInput.data("uiAutocomplete").close;
                searchInput.data("uiAutocomplete").close = function(event){
                    if(needToClose){
                        //只有在搜索结果重置时，才让其关闭
                        originalCloseMethod.apply( this, arguments );
                        needToClose = false;
                    }
                }
                predictList.delegate(".result-item","click",function(){
                    addPoiArea($(this).data("item"));
                });
                autocompleteResult.delegate(".result-item","click", function() {
                    addPoiArea($(this).data("item"));
                });
                function addPoiArea(data){

                    poiArea.html('<i class="left-icon poi-icons-'+(data.meta||'poi')+'_'+data.type+'_square"></i><span>'+data.label+'</span>');
                    
                    poiArea.attr({
                        'data-poi-id':data.id,
                        'data-poi-meta':data.meta,
                        'data-poi-type':data.type
                    }).removeClass('is-new-poi');

                    searchInput.val("").blur();
                    bt.misc.hidePopup(addPoiPop);
                }
                contentSearch.delegate('.add-new-poi','click',function(){
                    contentSwipe('right',function(){
                        //新增poi
                        PoiAdd.initAdd();
                    });
                });
            }

            var contentAdd = addPoiPop.find('.content-add'),
                addSearch = contentAdd.find('.search-map input'),
                addSearchBtn = contentAdd.find('.search-map-btn'),
                addPoiName = $('#add-poi-detail-name'),
                addPoiAddress = $('#add-poi-detail-address'),
                addPoiTel = $('#add-poi-detail-tel'),
                savePoiBtn = contentAdd.find('.save-poi'),
                cancelPoiBtn = contentAdd.find('.cancel-poi'),
                selectorPoi = $('#add-poi-poi-type'),
                selectorPoiPanel = $('#add-poi-poi-type-panel');
            var PoiAdd = {
                init : function(){
                    bt.gmap.initMapScript(this.initAddPOIPopupMapEvent);
                    savePoiBtn.click(function(){
                        if($(this).hasClass('disabled')){
                            return;
                        }
                        if(!$.trim(addPoiName.val())){
                            alert("请输入地点名称");
                            return;
                        }
                        if(!currentPoiInfo.lat && !currentPoiInfo.lng && !$.trim(addPoiAddress.val())){
                            alert("请输入详细地址");
                            return;
                        }
                        if(!selectorPoi.data('type')){
                            alert("请选择地点分类");
                            return;
                        }
                        
                        //新增poi
                        currentPoiInfo.id = 'new' + new_poi_index++ ;
                        currentPoiInfo.label =  $.trim(addPoiName.val());
                        currentPoiInfo.location = $.trim(addPoiAddress.val());
                        currentPoiInfo.tel = $.trim(addPoiTel.val());
                        currentPoiInfo.type = selectorPoi.data('type');
                        poiArea.html('<i class="left-icon poi-icons-'+(currentPoiInfo.meta||'poi')+'_'+currentPoiInfo.type+'_square"></i><span>'+currentPoiInfo.label+'</span>');
                        
                        poiArea.attr({
                            'data-poi-id':currentPoiInfo.id,
                            'data-poi-name':currentPoiInfo.label,
                            'data-poi-type':currentPoiInfo.type,
                            'data-poi-lat':currentPoiInfo.lat,
                            'data-poi-lng':currentPoiInfo.lng,
                            'data-poi-address': currentPoiInfo.location,
                            'data-poi-tel':currentPoiInfo.tel,
                        }).addClass('is-new-poi');
                        bt.misc.hidePopup(addPoiPop);
                        contentSwipe('left',function(){});
                    });
                    cancelPoiBtn.click(function(){
                        selectorPoiPanel.hide();
                        contentSwipe('left');
                    });
                    addSearch.keydown(function(e) {
                        var code = e.which;
                        if (code == 13) {
                            _searchAddress();
                            e.preventDefault();
                        }
                    });
                    addSearchBtn.click(function(){
                        _searchAddress();
                    });
                    function _searchAddress(){
                        addSearch.blur();
                        var address = addSearch.val();
                        if($.trim(address)) {
                            bt.gmap.searchAddress(poiMap, address, function(result) {
                                if(!poiMap.bteditable) {
                                    return;
                                }
                                var latLng = result[0].geometry.location;
                                PoiAdd._addMarker(latLng.lat(), latLng.lng(), poiMap, function(){
                                    addPoiAddress.val(currentPoiInfo.location);
                                });
                            });
                        }
                    }
                    selectorPoi.click(function(){
                        selectorPoiPanel.show();
                    });
                    selectorPoiPanel.find('li').not('.text').click(function(){
                        selectorPoi.find('.select-result').html($(this).html());
                        selectorPoi.data('type',$(this).data('type'));
                        selectorPoiPanel.hide();
                    });
                },
                initAdd :function(){
                    poiMap.bteditable = true;
                    bt.gmap.refreshMap(poiMap);
                    if(poiMarker) {
                        poiMarker.setMap(null);
                        poiMarker = null;
                    }
                    currentPoiInfo = {
                        id : 0,
                        value : '',
                        label : '',
                        location : '',
                        type : '',
                        meta : 'poi',
                        lat : '',
                        lng : '',
                        tel : ''
                    };
                    currentPoiObj = null;
                    bt.gmap.zoomToWorld(poiMap);

                    var address = $.trim(searchInput.val());
                    searchInput.val("").blur();
                    addPoiAddress.val('');
                    if ( currentMarker ) {
                        var _lat = currentMarker.getPosition().lat(),
                        _lng = currentMarker.getPosition().lng();
                        PoiAdd._addMarker(_lat, _lng, poiMap, function(){
                            addPoiAddress.val(currentPoiInfo.location);
                            bt.gmap.panTo(poiMap, _lat, _lng);
                        });
                    }
                    if(address) {
                        bt.gmap.searchAddress(poiMap, address, function(result) {
                            var latLng= result[0].geometry.location;
                            PoiAdd._addMarker(latLng.lat(), latLng.lng(), poiMap, function(){
                                addPoiAddress.val(currentPoiInfo.location);
                            });
                        });
                    }

                    addSearch.val(address || "");           
                    addPoiName.val(address || "");
                    addPoiTel.val("");
                    selectorPoi.data('type','');
                    selectorPoi.find('.select-result').html('选择地点分类');
                },
                initAddPOIPopupMapEvent : function(){
                    if(!google) {
                        return;
                    }
                    var myOptions = {
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    poiMap = bt.gmap.createMap("poi-map", myOptions);
                    bt.gmap.addListener(poiMap, 'click', function(event) {
                        if(!poiMap.bteditable) {
                            return;
                        }
                        PoiAdd._addMarker(event.latLng.lat(), event.latLng.lng(), poiMap,function(){
                            addPoiAddress.val(currentPoiInfo.location);
                        });
                    });
                },
                _addMarker : function (lat, lng, _map, saveCallback) {
                    var _self = this;
                    if(poiMarker) {
                        poiMarker.setMap(null);
                        poiMarker = null;
                    }
                    poiMarker = bt.gmap.addMarker(_map, lat, lng);
                    _self._refreshPOILocation(_map, saveCallback);
                    if(_map.bteditable) {
                        bt.gmap.addListener(poiMarker, 'dragend', function() {
                            _self._refreshPOILocation(_map, saveCallback);
                        });
                    } else {
                        bt.gmap.setOptions(poiMarker, {"draggable": false});
                    }
                },
                _refreshPOILocation : function(_map, saveCallback) {
                    if(!_map.bteditable) {
                        return;
                    }
                    var latLng = poiMarker.getPosition();

                    currentPoiInfo.lat = latLng.lat();
                    currentPoiInfo.lng = latLng.lng();

                    bt.gmap.convertCoordinateToGeo(latLng.lat(), latLng.lng(),
                        function(country_code, country, province, city) {
                            var text = ""
                                + jQuery.map([city, province, country],
                                           function(x) {
                                               return x? x: null;
                                           }).join(", ");
                            text = $.trim(text)? text: "位置";
                            currentPoiInfo.location = text;
                            if(saveCallback) {
                                saveCallback();
                            }
                        }
                    );
                }
            }

            initPopupDialog();
            initSearch();
            PoiAdd.init();
        },
        isWaypointEdited : function(){
            var old_lat = parseFloat(currentWaypointItem.attr('data-lat')),
                old_lng = parseFloat(currentWaypointItem.attr('data-lng')),
                new_lat = parseFloat(latitude.val()),
                new_lng = parseFloat(longitude.val());
            if( currentWaypointItem.attr('title') != text.val() ||
                currentWaypointItem.attr('data-poi-id') != poiArea.attr('data-poi-id') ||
                moment(currentWaypointItem.attr('data-time')).format() != moment(date.attr('data-time')).format() || 
                currentWaypointItem.attr('data-privacy') != privacy.val() || 
                currentWaypointItem.attr('data-tz-name') != timeSelect.val() ||
                (!old_lat && new_lat) ||
                (!old_lng && new_lng) ||
                Math.abs(old_lat - new_lat) > 1e-8 ||
                Math.abs(old_lng - new_lng) > 1e-8 ||
                currentWaypointItem.hasClass('new-text-item')){
                return true;
            }else{
                return false;
            }
        },
        initSubmitAndCancel : function(){
            $('#edit-waypoint-save-no').click(function(){
                Page.editWaypoint(currentWaypointItem,true);
            });
            editSaveYes.click(function(){
                var $this = $(this);
                if($this.hasClass('disabled')) return;
                if ( $this.html() == '正在保存' ) {
                    return;
                }
                if(!Page.isWaypointEdited()){
                    //编辑下一个waypoints
                    var wpItemlist = wpList.find('.wp-item'),
                        index = wpItemlist.index(currentWaypointItem),
                        nextItem = wpItemlist.eq(index + 1);
                    nextItem.trigger('click');
                    return;
                }
                $this.html('正在保存');
                var args = $("#edit-waypoint-form").serialize();
                var newPOIData = [],
                    linkInfo = [];
                //poi信息
                if(poiArea.hasClass('is-new-poi')){
                    newPOIData.push([
                        poiArea.attr('data-poi-id'),poiArea.attr('data-poi-name'),poiArea.attr('data-poi-type'),poiArea.attr('data-poi-lat'),poiArea.attr('data-poi-lng'),poiArea.attr('data-poi-address'),poiArea.attr('data-poi-tel')
                    ]);
                    args = args + "&" + $.param({new_poi_data : newPOIData});

                }else if( poiArea.attr('data-poi-id') && currentWaypointItem.attr('data-poi-id') != poiArea.attr('data-poi-id') ){
                    linkInfo.push([poiArea.attr('data-poi-meta')||'poi',poiArea.attr('data-poi-type'),poiArea.attr('data-poi-id')]);
                    args = args + "&" + $.param({link_poi_data : linkInfo}); 
                }
                //提交新增的文字waypoint
                if(currentWaypointItem.hasClass('new-text-item')){
                    var url = "/trips/" + bt.context('tripid') + "/waypoints/add/";
                    $.ajax({
                        url: url,
                        type: 'POST',
                        dataType: 'json',
                        data: args,
                        success: function (resp) {
                            if (resp.error_code) {
                                alert(resp.prompt);
                                editSaveYes.html('保存');
                            }else{
                                refreshCurrentWaypointItem(resp);
                                editSaveYes.html('保存');
                            }
                        }
                    });
                }else{
                    var url = "/trips/v1_1/" + bt.context('tripid') + "/waypoints/" + currentWaypointItem.data('id') + "/edit/";
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: args,
                        dataType: 'json',
                        success: function(resp) {
                            if(resp.error) {
                                alert(resp.error);
                                editSaveYes.html('保存');
                            } else {
                                refreshCurrentWaypointItem(resp);
                                editSaveYes.html('保存');
                            }
                        },
                        error: function() {
                        }
                    });
                }
                
            });
            function refreshCurrentWaypointItem(resp){
                Page.refreshMapPath(bt.context('tripid'));
                //如果时间改变了，则需要请求一次tripday列表，因为照片排序和时间列表改变了
                if(moment(currentWaypointItem.attr('data-time')).format() != moment(date.attr('data-time')).format() ||
                    currentWaypointItem.attr('data-tz-name') != timeSelect.val() ){
                    Page.refreshPhotoDayNav(true);
                }else{
                    //将设置的内容写回waypointitem
                    currentWaypointItem.attr({
                        'data-id': resp.waypoint.id,
                        'data-lat': latitude.val() || (resp.waypoint.location ? resp.waypoint.location.latitude : ""),
                        'data-lng': longitude.val() || (resp.waypoint.location ? resp.waypoint.location.longitude : ""),
                        'title': text.val(),
                        'data-privacy': privacy.val()
                    }).removeClass('new-text-item');
                    if(latitude.val() == "" && resp.waypoint.location){
                        Page.placeMarker(map, resp.waypoint.location.latitude, resp.waypoint.location.longitude);
                        bt.gmap.panTo(map, resp.waypoint.location.latitude, resp.waypoint.location.longitude);
                        $('#edit-waypoint-add-gps').addClass('hidden');
                    }
                    if(resp.poi){
                        currentWaypointItem.attr({
                            'data-poi-id': resp.poi.id,
                            'data-poi-name':resp.poi.name,
                            'data-poi-meta': 'poi',
                            'data-poi-type': resp.poi.category,
                        });
                        poiArea.attr('data-poi-id',resp.poi.id);
                    }
                    //编辑下一个waypoints
                    var wpItemlist = wpList.find('.wp-item'),
                        index = wpItemlist.index(currentWaypointItem),
                        nextItem = wpItemlist.eq(index + 1);
                    nextItem.trigger('click');
                }
            }
            $('#btn-next').click(function(e){
                e.preventDefault();
                if(currentWaypointItem && Page.isWaypointEdited() && !confirm('您有尚未保存的改动，确定离开？')){
                    return;
                }else{
                    Page.resetWaypointDetail();
                }
                var item = $(this),
                    redirect = item.attr("href");
                if ( bt.context('editId') ) {
                    redirect += "#wp" + bt.context('editId');
                }

                var data = bt.misc.initPostData();
                data["editing"] = bt.context('mode') ? true : false;
                $.ajax({
                    type: "POST",
                    data: data,
                    success: function(resp) {
                        if(resp.error) {
                            alert(resp.error);
                        } else {
                            if(resp.wp_ids.length > 0) {
                                var wid = resp.wp_ids[0],
                                item = wpList.find('.wp-item[data-id="'+wid+'"]');
                                item.trigger('click');
                                alert('请输入拍照时间');
                            } else {
                                window.location.href = redirect;
                            }
                        }
                    }
                });
                
            });
            $('#step2').click(function(){
                if(currentWaypointItem && Page.isWaypointEdited() && !confirm('您有尚未保存的改动，确定离开？')){
                    return;
                }else{
                    Page.resetWaypointDetail();
                    $(window).unbind("beforeunload");
                }
                var url = '/create_trip/'+bt.context('tripid')+'/link_poi/?start_id=0';
                if(bt.context('mode') == 'edit'){
                    url += '&mode=edit';
                }
                window.location.href = url;
            });
            $('#step1').click(function(){
                if(currentWaypointItem && Page.isWaypointEdited() && !confirm('您有尚未保存的改动，确定离开？')){
                    return;
                }else{
                    Page.resetWaypointDetail();
                    $(window).unbind("beforeunload");
                }
                window.location.href = '/trips/'+bt.context('tripid')+'/upload_photos/';
            });
        },
        refreshPhotoDayNav : function(jumpToNext){
            $.ajax({
                type: "get",
                url: "/create_trip/" + bt.context('tripid') + "/refresh_trip_days/",
                cache: false,
                data: {
                    csrfmiddlewaretoken : $('body').data('csrf')
                },
                success: function(resp) {
                    if(resp) {
                        isRefreshingPhotoList = true;
                        var currentId = currentWaypointItem.data('id'),
                            wpItemlist = wpList.find('.wp-item'),
                            index = wpItemlist.index(currentWaypointItem),
                            nextItemId = wpItemlist.eq(index + 1).data('id');
                        $('#tripdays-wrapper').empty().append(resp);
                        Page.initPhotoEvents();
                        var currentItem = wpList.find('.wp-item').filter('[data-id="'+currentId+'"]'),
                            nextItem = wpList.find('.wp-item').filter('[data-id="'+nextItemId+'"]');
                        if(jumpToNext){
                            //编辑下一个waypoints
                            nextItem.trigger('click');
                        }else{
                            currentItem.trigger('click');
                        }
                        editSaveYes.html('保存');
                    } else {
                       editSaveYes.html('保存');
                    }
                },
                error: function() {
                }
            });
        }
    };
    $(function(){
        bt.misc.initInputPlaceholder();
        Page.initPhotoEvents();
        Page.initWaypointDetail();
        Page.initAddPoiPopup();
        bt.gmap.initMapScript(Page.initMapEvents);
        Page.initSubmitAndCancel();
        $('body').scrollTop($('.edit-waypoint').offset().top);
    });
    $(window).on('beforeunload', function() {
        if( Page.isWaypointEdited() ){
            return "您有尚未保存的改动，确定离开？";
        }
    });
}});
